using Unity.Burst;
using Unity.Collections;
using Unity.Entities;
using Unity.Mathematics;
using Unity.Transforms;

namespace DOTS.DOD.LESSON4
{
    [BurstCompile]
    [UpdateInGroup(typeof(WaveCubeWithDotsSystemGroup))]
    public partial struct WaveCubeGenerateSystem : ISystem
    {
        [BurstCompile]
        public void OnCreate(ref SystemState state)
        {
            state.RequireForUpdate<WaveCubeGenerator>();
        }

        [BurstCompile]
        public void OnUpdate(ref SystemState state)
        {
            var generator = SystemAPI.GetSingleton<WaveCubeGenerator>();
            var cubes = CollectionHelper.CreateNativeArray<Entity>(4 * generator.RadiusX * generator.RadiusZ,
                Allocator.Temp);
            state.EntityManager.Instantiate(generator.CubeProtoType, cubes);

            int count = 0;
            foreach (var cube in cubes)
            {
                int x = count % (generator.RadiusX * 2) - generator.RadiusX;
                int z = count / (generator.RadiusX * 2) - generator.RadiusZ;
                var pos = new float3(x * 1.1f, 0, z * 1.1f);
                
                //方法一：
                // var transform = SystemAPI.GetAspectRW<TransformAspect>(cube);
                // transform.LocalPosition = pos;
                
                //方法二：
                var cubeAspect = SystemAPI.GetAspect<WaveCubeAspect>(cube);
                cubeAspect.SetPos(pos);
                
                count++;
            }

            cubes.Dispose();
            state.Enabled = false; //只运行一次
        }
    }
}